<template>
	<view class="container">
		<view class="header">
			<view class="header-title-left">欢迎来到盐池零工平台自助系统</view>
			<view class="back" @click="goBack"><uni-icons type="left" size="30"></uni-icons>返回</view>
			<view class="header-title">
				<view>请务工人员扫描证件</view>
				<!-- <view @click="handldUser">添加人员</view> -->
			</view>
		</view>

		<view class="content">

			<!-- 招工人员 -->
			<view class="mess">
				<view class="head">
					<image :src="user.photo" mode=""></image>
				</view>
				<view class="value">
					<view class="value_left">
						<view class="title" id="tag">{{ user.userName }}
							<text class="sex"> {{ user.sex }} </text> <uni-tag text="招工人员" type="primary"
								custom-style="width: 120px; padding: 5px; margin-left: 20px; font-size: 28px" />
						</view>
						<view>身份证号：{{ user.desensitizationCard }}</view>
						<view>户籍地址：{{ user.address }}</view>
						<view>身份证有效期：{{ user.idCardExpirationDate }}</view>
					</view>
				</view>
			</view>

			<!-- 务工人员 -->
			<view class="mess" v-for="(item,index) in newCardList" :key="index">
				<view class="head">
					<image :src="item.photo" mode=""></image>
				</view>
				<view class="value">
					<view class="value_left">
						<view class="title">{{ index + 1 }}、{{ item._PeopleName }} <text class="sex">{{ item._Sex }}</text>
							<uni-tag text="务工人员" type="warning"
								custom-style="width: 120px; padding: 5px; margin-left: 20px; font-size: 28px" />
						</view>
						<view>身份证号：{{ item.desensitizationCard }}</view>
						<view>户籍地址：{{ item._Addr }}</view>
						<view>身份证有效期：{{ item._StartDate }} - {{ item._EndDate }}</view>
					</view>
					<view class="value_right" @click="del(item,index)"></view>
				</view>
			</view>

		</view>
		<Footer @click="submit('baseForm')">确认用工</Footer>



		<Message />
		<!-- <button class="footer-button" @click="submit('baseForm')">确认用工</button> -->

		<view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popup" background-color="#fff" borderRadius="10px 10px 10px 10px" class="popup">
				<view class="popup-content">
					<image class="popup-image-icon" src="../../static/images/success.png"></image>
					<view class="popup-title">
						零工招募完成，感谢您的使用
					</view>
					<view class="popup-title">
						{{ countdown }}s 后自动退出系统
					</view>
					<view class="popup-buttons">
						<button style="color:#ffffff;backgroundColor:#EF7754;borderColor:none" @click="loginOut">退出登陆</button>
						<button style="color:#ffffff;backgroundColor:#4B81FF;borderColor:none" @click="look">再次发布</button>
					</view>
					<image class="popup-footer-icon" src="../../static/images/icon-left.png"></image>
				</view>
			</uni-popup>
		</view>

	</view>

</template>

<script>
	import {
		logOut
	} from '@/api/home/index';
	import {
		findNxLevel4Tree,
		findTypeCascade,
		publish
	} from '@/api/company/index.js';
	import zzld from '../../utils/zzld.js';
	import {
		fastRegister,
		fastRecruit
	} from '@/api/fast/index.js';
	import {
		desensitizeChineseName,
		validateAndDesensitizeIDCard
	} from 'utils/custom.js';
	export default {
		components: {
			Message: () => import('../common/message.vue'),
			Footer: () => import('../common/bottom.vue')
		},
		data() {
			return {
				user: {
					head: ''
				},
				tokenId: '',
				// 基础表单数据
				baseFormData: {
					photo: '',
					code: '',
					industry: '',
				},
				// 务工人员列表
				cardList: [],
				newCardList: [],
				// 快速发布的岗位id
				gigJobId: 0,
				// 务工人员快速登陆后的id   提交时  workerIds
				ids: [],
				// 用于快速查找 _IDCard 是否已存在
				idCardSet: new Set(),
				isPublish: false,
				timer: null,
				intervalTime: 5000,
				countdown: 5,
			}
		},
		onLoad() {
			this.getInit();
			this.audio();
			this.initReadCard();
		},
		onHide() {
			console.log('页面隐藏');
			// 确保在页面卸载时清理资源
			this.cleanupReadCard();
			this.clearCountdown();
		},
		onUnload() {
			console.log('页面卸载');
			// 确保在页面卸载时清理资源
			this.cleanupReadCard();
			this.clearCountdown();
		},
		methods: {

			audio(src) {
				let audios = uni.createInnerAudioContext();
				audios.src = require('../../static/audio/请参与人3.mp3');
				audios.play();
			},
			audio_1(src) {
				let audios = uni.createInnerAudioContext();
				audios.src = require('../../static/audio/完成零工4.mp3');
				audios.play();
			},
			audioDing() {
				let audios = uni.createInnerAudioContext();
				audios.src = require('../../static/audio/ding_5.mp3');
				audios.play();
			},
			getInit() {
				this.tokenId = uni.getStorageSync('tokenId');
				this.gigJobId = uni.getStorageSync('gigJobId');
				let result = uni.getStorageSync('user');
				const name = desensitizeChineseName(result.userName);
				const {
					isValid,
					desensitizedIDCard
				} = validateAndDesensitizeIDCard(result.idCard);
				this.user = {
					...result,
					photo: `${result.photo}`,
					userName: name,
					desensitizationCard: desensitizedIDCard
				};
			},

			initReadCard() {
				zzld.init(); // 重新初始化 zzld
				this.bindCallbacks(); // 绑定B页面特有的回调
			},
			cleanupReadCard() {
				// 清理全局对象上的方法
				if (window.zzld) {
					window.zzld = null;
				}
				console.log('window.zzld', window);
				delete window.startReadCard;
			},
			del(item, index) {
				uni.showModal({
					title: '删除',
					content: `确认要删除 【${item._PeopleName}】_【${item._IDCard}】的务工人员吗？`,
					success: async (res) => {
						if (res.confirm) {
							console.log("用户点击了确定");
							this.newCardList.splice(index, 1); // 第一个参数是起始索引，第二个参数是要删除的项数
							this.idCardSet.delete(item._IDCard);
							this.ids.splice(index, 1)
							console.log('this.idCardSet', this.idCardSet);
						} else if (res.cancel) {
							console.log("用户点击了取消");
						}
					}
				})
			},

			initReadCard() {
				zzld.init(); // 重新初始化 zzld
				this.bindCallbacks(); // 绑定B页面特有的回调
			},
			bindCallbacks() {
				// 绑定B页面特有的回调
				zzld.readIdCardCallback = async (res) => {
					await this.handleIdCardData(res);
				};
			},
			startReadCard() {
				zzld.showToast("==开始读卡==");
				zzld.startReadIdCard();
			},
			async handleIdCardData(res) {
				zzld.showToast(".....读取数据...");
				this.audioDing();
				console.log('handleIdCardData--录取务工人员信息');
				if (res) {
					const head = this.headParse(res);
					const data = this.infoParse(res);




					const {
						_IDCard
					} = data;

					// 判断是否和当前用户一样
					if (this.user.idCard === _IDCard) {
						uni.showToast({
							title: '该身份证已是招工人员，不可为务工人员',
							icon: 'none'
						});
						return false;
					}

					// 判断是否重复
					if (this.idCardSet.has(_IDCard)) {
						console.log('重复的身份证信息已存在:', _IDCard);
						// 可以选择在此处提示用户或者采取其他行动
						uni.showToast({
							title: '数据不能重复，请换身份证',
							icon: 'none'
						});

						return false;
					}

					// 没有重复  登陆
					const newData = {
						address: data._Addr,
						idCard: data._IDCard,
						idCardExpirationDate: data._StartDate + ' - ' + data._EndDate,
						issuingAuthority: data._Department,
						nation: data._People,
						photo: head,
						userName: data._PeopleName,
						sex: data._Sex,
						gigJobId: this.gigJobId,

					}
					// 整理数据并登陆 操作
					fastRegister(newData).then((res) => {
						console.log('整理数据并登陆', res.data.useId);
						this.ids.push(res.data.useId);
					})

					const name = desensitizeChineseName(data._PeopleName);
					const {
						isValid,
						desensitizedIDCard
					} = validateAndDesensitizeIDCard(data._IDCard);

					this.newCardList.push({
						...data,
						photo: head,
						userName: name,
						desensitizationCard: desensitizedIDCard
					})
					this.idCardSet.add(_IDCard); // 同步更新 Set

				}
			},

			// 读卡
			startReadCard() {
				zzld.showToast("==开始读卡==")
				zzld.startReadIdCard(async (res) => {
					zzld.showToast(".....读取数据...");
					this.audioDing();
					console.log('startReadCard--录取务工人员信息', );
					if (res) {

						const data = this.infoParse(res);
						const head = this.headParse(res);


						// 判断是否重复
						const {
							_IDCard
						} = data;

						// 判断是否和当前用户一样
						if (this.user.idCard === _IDCard) {
							uni.showToast({
								title: '该身份证已是招工人员，不可为务工人员',
								icon: 'none'
							});
							return false;
						}


						if (this.idCardSet.has(_IDCard)) {
							console.log('重复的身份证信息已存在:', _IDCard);
							// 可以选择在此处提示用户或者采取其他行动
							uni.showToast({
								title: '数据不能重复，请换身份证',
								icon: 'none'
							});

							return false;
						}



						// 没有重复  登陆
						const newData = {
							address: data._Addr,
							idCard: data._IDCard,
							idCardExpirationDate: data._StartDate + ' - ' + data._EndDate,
							issuingAuthority: data._Department,
							nation: data._People,
							photo: head,
							userName: data._PeopleName,
							sex: data._Sex,

						}

						// 整理数据并登陆 操作
						fastRegister(newData).then((res) => {
							console.log('整理数据并登陆', res.data.useId);
							this.ids.push(res.data.useId);
						})

						const name = desensitizeChineseName(data._PeopleName);
						const {
							isValid,
							desensitizedIDCard
						} = validateAndDesensitizeIDCard(data._IDCard);
						this.newCardList.push({
							...data,
							head: head,
							userName: name,
							desensitizationCard: desensitizedIDCard
						})
						this.idCardSet.add(_IDCard); // 同步更新 Set
					}
				})

			},
			maskClick(e) {
				console.log('maskClick事件:', e);
			},
			goBack() {
				uni.navigateBack();
				return;
			},

			submit(ref) {
				const array = this.ids;
				if (array.length === 0) {
					uni.showToast({
						title: '务工人员列表为空，请扫证',
						icon: 'none'
					});
					return;
				}
				const data = {
					gigJobId: this.gigJobId,
					workerIds: this.ids,
				}
				fastRecruit(data).then((res) => {
					this.$refs.popup.open('center');
					this.isPublish = true;
					this.audio_1();
				}).catch((res) => {
					uni.showToast({
						title: '发布失败',
						icon: 'error'
					})
				})
			},
			look() {
				this.$refs.popup.close();
				this.clearCountdown();
				uni.$u.route({
					url: 'pages/fast/index'
				})
			},
			loginOut() {
				logOut(this.tokenId).then(() => {
					uni.removeStorageSync('user');
					uni.removeStorageSync('token');
					uni.showToast({
						title: '退出成功'
					})
					this.$refs.popup.close();
					uni.$u.route({
						url: 'pages/home/index'
					})
				}).catch(() => {
					uni.showToast({
						title: '退出失败'
					})
					this.$refs.popup.close();
				})
			},



			infoParse(str) {
				// 使用正则表达式提取 info 后面的内容
				const match = str.match(/"info"\s*:\s*({[^}]*})/);

				if (match && match[1]) {
					const infoString = match[1];
					console.log(infoString); // 输出: {"name": "123","sex": "男"}

					// 如果需要将提取的字符串转换为对象
					try {
						const infoObject = JSON.parse(infoString);
						console.log(infoObject); // 输出: { name: '123', sex: '男' }
						return infoObject
					} catch (error) {
						console.error("Error parsing JSON:", error.message);
					}
				} else {
					console.log('No match found');
				}
			},

			headParse(jsonString) {
				// 使用正则表达式提取 head 后面的内容，包括双引号
				let result = "data:image/png;base64," + jsonString.split('"head":"')[1].split('"')[0];
				return result.replace(/[\r\n]/g, '').trim();
			},

			// 判断 当前列表里面  身份证信息是否重复
			checkingForDuplicates(id) {
				const isRepetition = this.newCardList.find((item) => item._IDCard === id)
			},

			startTimer() {
				// 清除可能存在的旧定时器
				this.clearCountdown();

				// 启动新的定时器

				this.timer = setInterval(() => {
					if (this.countdown > 0) {
						this.countdown--;
					} else {
						this.onCountdownEnd();
					}
				}, 1000);

			},
			onCountdownEnd() {
				console.log('倒计时结束');
				this.clearCountdown();
				this.$refs.popup.close();
				this.loginOut();
				this.isPublish = false; // 可选：倒计时结束后自动关闭倒计时
			},
			clearCountdown() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},
		},
		watch: {
			isPublish(newValue) {
				console.log('newValue', newValue);
				if (newValue) {
					this.startTimer();
				} else if (this.timer) {
					this.clearCountdown();
				}
			}
		},
	}
</script>

<style lang="less" scoped>
	/* 基础样式 */
	body,
	page {
		font-family: Arial, sans-serif;
		background-color: #f4f6fa;
		margin: 0;
		padding: 0;
	}

	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		// justify-items: center;
		height: 100vh;
		/* background-color: #CBE1FB; */
		/* 背景颜色 */
		background-image: url('../../static/images/background_2.png');
		/* 背景图片 */
		// background-size: cover;
		background-position: center;
		background-blend-mode: multiply;
		/* 背景混合模式，使颜色和图片叠加 */
	}

	.header {
		padding: 50px;
		width: 90%;

		.header-title-left {
			text-align: left;
			font-size: 32px;
			color: #384161;
			width: 100%;
		}

		.header-title {
			text-align: center;
			font-size: 100px;
			font-weight: 600;
			color: #4B81FF;
			width: 100%;
			margin: 100px auto 0px;
			/* 使文本居中时占据整行 */
			position: relative;
		}

		.back {
			position: absolute;
			font-size: 24px;
			color: #384161;
			line-height: 0px;
			width: 80px;
			height: 40px;
			left: 46px;
			top: 120px;
			/* 自动布局 */
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			border: 1px solid #fff;
			box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
			padding: 8px 24px 8px 24px;
		}
	}



	.content {
		width: 95%;
		height: 70vh;
		overflow-y: auto;
		margin: 0 auto;

		.mess {
			display: flex;
			align-items: center;
			width: 95%;
			padding: 20rpx;
			margin: 20rpx;
			border: 2px solid #e6e6e6;
			box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1);
			border-radius: 8px;
			// background-color: white;



			.head {
				width: 35%;
				padding: 10rpx;
			}

			.value {
				width: 65%;
				height: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;

				view {
					font-size: 44rpx;
					// color: #4B81FF;
					margin: 20rpx;
					padding: 10rpx;
				}

				.value_left {
					width: 85%;
					// display: flex;

					.title {
						font-size: 60rpx;
						font-weight: bold;
					}

					.sex {
						margin-left: 40rpx;
						font-size: 58rpx;
						color: #87a0fb;
					}

					// .value

				}

				.value_right {
					width: 100rpx;
					height: 100rpx;
					background: url('../../static/images/delete.png');
					background-size: 100%;
					background-position: 100% 100%;
					background-repeat: no-repeat;
				}
			}

		}
	}




	.popup-content {
		height: 850px;
		width: 850px;
		padding: 50px;
		border-radius: 10px;
		text-align: center;
		background-color: #DBEAFB;
		background-image: url('../../static/images/card_bg.png');
		background-repeat: no-repeat;
		background-size: 100% 100%;
		position: relative;

		.popup-image-icon {
			width: 302px !important;
			height: 266px !important;
			margin: 150px auto 50px;
		}

		.popup-title {
			// display: flex ;
			text-align: center;
			font-size: 34px;
			font-weight: 600;
			color: #384161;
			line-height: 32px;
			margin: 0px auto 50px;
			position: relative;
		}

		.popup-buttons {
			display: flex;
			justify-content: center;
			margin-top: 200px;

			button {
				width: 200px;
				margin-left: 0;
				margin-right: 20px;
			}
		}

		.popup-image {
			width: 630px;
			border-radius: 20px;
			margin: 150px auto;
			height: 380px;
			padding: 50px 50px;
			background: linear-gradient(to bottom, #FFFFFFFF, #ECF6FEFF);
			display: flex;
			text-align: center;

			.popup-image-left {
				width: 34%;
				text-align: left;

				.title {
					font-size: 36px;
					font-weight: 600;
					line-height: 60px;
				}

				.sub-title {
					font-size: 24px;
					font-weight: 500;
					line-height: 60px;
					color: #687792;
				}

				.sub-gang {
					width: 68px;
					right: 566px;
					height: 4px;
					margin-top: 60px;
					border-radius: 16px;
					background: #d4dadf;
				}
			}

			.popup-image-right {
				margin: auto;
			}
		}

		.popup-footer-icon {
			width: 200px;
			height: 150px;
			position: absolute;
			left: 0px;
			bottom: 0px;
		}
	}

	.footer-button {
		position: fixed;
		right: 40px;
		bottom: 20px;

		width: 120px;
		background-color: #4B81FF;
		color: #fff;
		margin-right: 0 !important;
	}


	#tag {
		::v-deep .uni-tag {
			border: 1xp solid red !important;
		}
	}
</style>